package com.a2j.sys.user.service.impl;

import com.a2j.beans.base.BaseBean;
import com.a2j.beans.base.code.ResponseCode;
import com.a2j.beans.user.SysUser;
import com.a2j.exception.BizException;
import com.a2j.sys.user.mapper.SysUserMapper;
import com.a2j.sys.user.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Author: bzb
 * Data: 2021/10/24 00:00
 * Desc: 系统用户实现
 */
@Service
public class SysUserImpl implements SysUserService {

    @Resource
    SysUserMapper mapper;

    @Override
    public BaseBean<List<SysUser>> allUser() {
        return BaseBean.success(mapper.allUser());
    }

    @Override
    public void register(SysUser record) {
        Assert.notNull(record, "用户对象为空！");
        Assert.hasLength(record.getUsername(), "用户名为空！");
        Assert.hasLength(record.getPassword(), "密码为空！");
        Assert.hasLength(record.getPhone(), "手机号为空！");

        // 查询该用户是否存在
        SysUser user = mapper.findUserByAccount(record.getUsername());
        if (user != null && user.getEnable() == 1) {
            throw new BizException(ResponseCode.NO_DATA.getCode(), "系统用户已存在, 请直接登录！");
        }

        // TODO: 2021/10/21
        // 生成盐值
        record.setSalt("");
        // 多种业务场景处理，例如：注销的用户重新激活

        record.setId(null); // 主键置空

        int result = mapper.register(record);
        if (result == 0) {
            throw new BizException(ResponseCode.NO_DATA.getCode(), "注册失败！");
        }
    }

    @Override
    public BaseBean<SysUser> login(String username, String password) {
        Assert.hasLength(username, "用户名为空！");
        Assert.hasLength(password, "密码为空！");

        // 查询该用户是否存在
        SysUser user = mapper.findUserByAccount(username);
        if (user == null) throw new BizException(ResponseCode.NO_DATA.getCode(), "系统用户不存在！");

        // 判断用户是否可操作
        if (user.getEnable() == 0) {
            throw new BizException(ResponseCode.FAILED_UPDATE.getCode(), "黑名单用户，不可修改！");
        }

        // TODO: 2021/10/20  取盐值，匹配密码

        // 二次校验查询
        user = mapper.login(username, password);
        if (user == null) throw new BizException(ResponseCode.NO_DATA.getCode(), "密码错误，登录失败！");

        int result = mapper.updateUser(
                SysUser.builder()
                        .id(user.getId())
                        .lastLoginTime(new Date())
                        .build()
        );

        if (result == 0) throw new BizException(ResponseCode.FAILED_UPDATE);

        // 反复刷接口的情况
        // 动态获取用户的权限
        // 生成新的token，存储到Redis （jwt的成本问题）

        // 密码置空不返回到前端
        user.setPassword(null);
        return BaseBean.success(user);
    }

    @Override
    public BaseBean<SysUser> sysUserDetail(Integer userId) {
        Assert.notNull(userId, "用户ID为空！");
        SysUser user = mapper.findUserById(userId);
        if (user == null) throw new BizException(ResponseCode.NO_DATA);

        // 密码置空不返回到前端
        user.setPassword(null);
        return BaseBean.success(user);
    }

    @Override
    public void changePassword(Integer id, String oldPwd, String newPwd) {
        Assert.notNull(id, "用户ID为空！");
        Assert.hasLength(oldPwd, "旧密码为空！");
        Assert.hasLength(newPwd, "新密码为空！");

        // 根据用户id查询
        SysUser user = mapper.findUserById(id);
        if (user == null) throw new BizException(ResponseCode.NO_DATA);

        // 判断用户是否可操作
        if (user.getEnable() == 0) {
            throw new BizException(ResponseCode.FAILED_UPDATE.getCode(), "黑名单用户，不可修改！");
        }

        // TODO: 2021/10/20
        // 匹配密码过程（加盐）
        // 旧密码匹配，则生成新的盐值

        // 修改密码
        int result = mapper.updateUser(
                SysUser.builder()
                        .id(id)
                        .password(newPwd)
                        .lastLoginTime(new Date())
                        .build()
        );

        if (result == 0) throw new BizException(ResponseCode.FAILED_UPDATE);
    }

    @Override
    public void enable(Integer id, Integer enable) {
        Assert.notNull(id, "用户ID为空！");
        if (enable == null) enable = 0;

        int result = mapper.updateUser(
                SysUser.builder()
                        .id(id)
                        .enable(enable)
                        .lastLoginTime(new Date())
                        .build()
        );

        if (result == 0) throw new BizException(ResponseCode.FAILED_UPDATE);
    }

    @Override
    public void updateUser(SysUser record) {
        Assert.notNull(record, "用户对象为空！");
        Assert.notNull(record.getId(), "用户ID为空！");

        int result = mapper.updateUser(record);
        if (result == 0) throw new BizException(ResponseCode.FAILED_UPDATE);
    }
}
